package com.hube.platform.tenant.helper;

import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Slf4jReporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * hikariCP 监控，打印到日志里面，采取web端输出的方式，弃用
 *
 * @author : Aaron
 * @date : 2022/6/9
 */
@Deprecated
public class MetricRegistryBuilder {

    private static final Logger log = LoggerFactory.getLogger(MetricRegistryBuilder.class);

    /**
     * 配置指标监控
     *
     * @param poolName
     * @return
     */
    public static MetricRegistry build(String poolName) {
        MetricRegistry metricRegistry = new MetricRegistry();
        WhitelistMetricFilter whitelistMetricFilter = new WhitelistMetricFilter(Arrays.asList("ActiveConnections", "TotalConnections", "IdleConnections"));
        Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry)
                .filter(whitelistMetricFilter)
                .outputTo(log)
                .convertRatesTo(TimeUnit.SECONDS)
                .convertDurationsTo(TimeUnit.MILLISECONDS)
                .build();
        reporter.start(300, TimeUnit.SECONDS);
        return metricRegistry;
    }

    /**
     * 条件筛选过滤器
     */
    private static class WhitelistMetricFilter implements MetricFilter {
        private final List<String> whitelist;

        public WhitelistMetricFilter(List<String> whitelist) {
            this.whitelist = whitelist;
        }

        @Override
        public boolean matches(String name, Metric metric) {
            for (String whitelisted : whitelist) {
                if (name.endsWith(whitelisted))
                    return true;
            }
            return false;
        }
    }
}
